package com.zzl.study.nacos.discovery;

import lombok.NoArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务实例缓存工具
 *
 * @author: zhangzl
 * @date: 2025/7/16 14:07
 * @version: 1.0
 */
public final class ServiceCache {

    /**
     * 私有构造方法
     */
    private ServiceCache() {
    }

    /**
     * 服务缓存集合
     */
    private static List<String> services = Collections.emptyList();

    /**
     * 服务实例缓存集合
     */
    private static Map<String, List<ServiceInstance>> instancesMap = new ConcurrentHashMap<>();

    /**
     * 设置服务实例缓存
     *
     * @param serviceId 服务ID
     * @param instances 服务实例
     */
    public static void setInstances(String serviceId, List<ServiceInstance> instances) {
        instancesMap.put(serviceId, Collections.unmodifiableList(instances));
    }

    /**
     * 获取服务实例缓存
     *
     * @param serviceId 服务ID
     * @return 服务实例
     */
    public static List<ServiceInstance> getInstances(String serviceId) {
        return Optional.ofNullable(instancesMap.get(serviceId)).orElse(Collections.emptyList());
    }

    /**
     * 设置服务缓存
     *
     * @param serviceIds 服务ID集合
     */
    public static void setServiceIds(List<String> serviceIds) {
        services = Collections.unmodifiableList(serviceIds);
    }

    /**
     * 获取服务缓存
     *
     * @return 服务ID集合
     */
    public static List<String> getServiceIds() {
        return services;
    }

}
